/**
 * Created by huangzx on 2015/12/7.
 */
define(['angular',
        'underscore',
        'system2/rule/ProjectController',
        'system2/rule/PackageController',
        'system2/rule/AssemblyController',
        'system2/rule/DecisionTableController',
        'system2/rule/DecisionTreeController',
        'system2/rule/DecisionEditController',
        'system2/rule/DecisionTreeEditController',
        'system2/rule/RuleController',
        'system2/rule/setting/RulePackageInstallController',
        'system2/rule/setting/RuleInstallController',
        'system2/rule/setting/RuleAssemblyInstallController',
        'system2/rule/setting/DecisionTableInstallController',
        'system2/rule/setting/DecisionTreeInstallController',
        'system2/rule/setting/VariableController',
        'system2/version/VersionController',
        'system2/unitcases/TestController',
        'system2/model/AttributeController',
        'system2/component/JdbcController',
        'system2/component/RemoteController',
        'system2/component/DubboController',
        'system2/component/SpringCloudController',
        'system2/component/GroovyShellController',
        'system2/component/ValidatorController',
        'system2/Hash',
        'angular-route',
        'framework/msg/GillionMsgModule',
        'framework/rule/RuleModule',
        'framework/dataGrid/DataGridModule',
        'framework/pagination/GillionPaginationModule',
        'angular-local-storage',
        'bootstrap',
        'framework/date/DateModule',
        'framework/dropdown/GillionDropdownModule',
        'system2/RulePermissionModule',
        'system2/RuleStatusModule',
        'jquery-sortable',
        'angular-ui-tree'
    ],
    function (angular,
              _,
              ProjectController,
              PackageController,
              AssemblyController,
              DecisionTableController,
              DecisionTreeController,
              DecisionEditController,
              DecisionTreeEditController,
              RuleController,
              RulePackageInstallController,
              RuleInstallController,
              RuleAssemblyInstallController,
              DecisionTableInstallController,
              DecisionTreeInstallController,
              VariableController,
              VersionController,
              TestController,
              AttributeController,
              JdbcController,
              RemoteController,
              DubboController,
              SpringCloudController,
              GroovyShellController,
              ValidatorController,
              Hash) {
        var app = angular.module('MainModule', ['ngRoute', 'GillionMsgModule','RuleModule', 'LocalStorageModule', 'DataGridModule', 'GillionPaginationModule', 'RulePermissionModule','RuleStatusModule','DateModule','GillionDropdownModule','ui.tree']);
        app.filter("typeFilter",function(){
            return function(input){
                if(input==0){
                    return "数字"
                }
                if(input==1){
                    return "字符串"
                }
                if(input==2){
                    return "布尔型"
                }
                if(input==3){
                    return "对象"
                }
            }
        })
        angular.element(document).on('click', '.engine-tab li', function () {
            var nav = angular.element(this),
                key = nav.data('key'),
                tab = angular.element('div.engine-tab-content[data-key="' + key + '"]');
            nav.addClass('on').siblings('.on').removeClass('on');
            tab.show();
            tab.siblings('div.engine-tab-content').hide();
        });

        /*angular.element(document).on('click', 'a,button', function ($GillionMsg,$rootScope) {
            var $noMes = angular.element(this).parents('.no-mes');
            if ($noMes.length == 0) {
                console.log("---");
                return false;
                /!*$GillionMsg.alert("提示", "项目新建成功");*!/
            }
        });*/

        app.factory('RuleSerivce', function ($rootScope, $http, $location, $routeParams, $q, Arrays) {
            return {
                setCurrentProject: function (project) {
                    $rootScope.currProjcet = project;
                },
                setCurrentPackage: function (pg) {
                    $rootScope.currPackage = pg;
                },
                setCurrentAssembly: function (assembly) {
                    $rootScope.currAssembly = assembly;
                },
                setCurrentRule: function (rule) {
                    $rootScope.currRule = rule;
                },
                setVariableScope: function (id) {
                    $rootScope.variableScope = id;
                },
                setCurrentDecisionTable: function (decisionTable) {
                    $rootScope.currDecisionTable = decisionTable;
                },
                setCurrentDecisionTree: function (decisionTree) {
                    $rootScope.currDecisionTree = decisionTree;
                },
                setIsMes: function (isMes) {
                    $scope.isMes = isMes;
                },

                getRulePackageMenu: function (packageId) {
                    if (packageId) {
                        $http.get('/grule-manager/rulePackage/getRulePackageMenu/' + packageId).success(function (resp) {
                            $rootScope.menus =  _.sortBy(resp.data, function(menu){
                                return menu.priority;
                            });
                        });
                    }
                },
                readyData: function () {
                    var projectId = $routeParams.projectId,
                        packageId = $routeParams.packageId,
                        assemblyId = $routeParams.assemblyId,
                        ruleId = $routeParams.ruleId,
                        tableId = $routeParams.tableId,
                        treeId = $routeParams.treeId,
                        result = {},
                        promises = [];

                    if (projectId && !$rootScope.currProjcet) {
                        result['project'] = $q.defer();
                        $http.get('/grule-manager/projects/' + projectId).success(function (resp) {
                            if (resp) {
                                $rootScope.currProjcet = resp;
                                result['project'].resolve(resp);
                            }
                        });
                    }

                    if (packageId) {
                        result['package'] = $q.defer();
                        $http.get('/grule-manager/rulePackage/' + packageId).success(function (resp) {
                            if (resp) {
                                $rootScope.currPackage = resp;
                                result['package'].resolve(resp);
                            }
                        });
                    }

                    if (assemblyId) {
                        result['assembly'] = $q.defer();
                        $http.get('/grule-manager/ruleAssembly/' + assemblyId).success(function (resp) {
                            if (resp) {
                                $rootScope.currAssembly = resp;
                                result['assembly'].resolve(resp);
                            }
                        });
                    }

                    if (ruleId) {
                        result['rule'] = $q.defer();
                        $http.get('/grule-manager/rule/' + ruleId).success(function (resp) {
                            if (resp) {
                                $rootScope.currRule = resp;
                                result['rule'].resolve(resp);
                            }
                        });
                    }

                    if (tableId) {
                        result['decisionTable'] = $q.defer();
                        $http.get('/grule-manager/decision-tables/' + tableId).success(function (resp) {
                            if (resp.success) {
                                $rootScope.currDecisionTable = resp.data;
                                result['decisionTable'].resolve(resp.data);
                            }
                        });
                    }

                    if (treeId) {
                        result['decisionTree'] = $q.defer();
                        $http.get('/grule-manager/decisionTrees/' + treeId).success(function (resp) {
                            if (resp.success) {
                                $rootScope.currDecisionTree = resp.data;
                                result['decisionTree'].resolve(resp.data);
                            }
                        });
                    }
                    angular.forEach(result, function(defer){
                        promises.push(defer.promise);
                    });
                    $rootScope.dataPromise = $q.all(promises);

                    if (packageId) {
                        $rootScope.showBtns = true;
                    } else {
                        $rootScope.showBtns = false;
                    }
                },

                promises: function(){
                    return $rootScope.dataPromise;
                }
            }
        });



        app.controller('HeaderController', ['$scope', '$rootScope', '$location', '$http', 'GillionMsg', '$routeParams', 'Resource', 'Permissions','RuleSerivce', function ($scope, $rootScope, $location, $http, GillionMsg, $routeParams, Resource, Permissions,RuleSerivce) {
            angular.element(document).off('refresh.menu').on('refresh.menu', function() {
                if ($routeParams.packageId) {
                    RuleSerivce.getRulePackageMenu($routeParams.packageId);
                }
            });





            var permission=Resource("/grule-manager/permissions/getPermissions");
            $scope.monitorShow=true;
            $scope.account = $rootScope.$sessionAttrs.loginUser;
            $scope.currUser = $scope.account.username;
            $scope.showCompile=false;
            $scope.showTest=false;
            $scope.showPublish=false;
            $scope.$watch('headerPackageId',function(newValue,oldValue){
                if(newValue!=oldValue){
                    permission.get({packageId:newValue},function(response){
                        if(response.data.success==true){
                            $scope.showCompile=true;
                            $scope.showTest=true;
                            $scope.showPublish=true;
                        }else{
                            $scope.showCompile=false;
                            $scope.showTest=false;
                            $scope.showPublish=false;
                        }
                    })
                }
            })
            $scope.compile = function () {
                var rowId = $routeParams.packageId;
                GillionMsg.confirm('提示信息', '是否确定编译？',
                    function (r) {
                        if (r) {
                            Resource("/grule-manager/rulePublish/compile/:id", {
                                id: "@id"
                            }, {
                                "get": {
                                    "failHandler": false
                                }
                            }).get({
                                id: rowId
                            }, function (response) {
                                GillionMsg.showUrl({
                                    title: '编译结果',
                                    url: '/html2/execute/compile',
                                    data: {log: response},
                                    height: 400,
                                    width: 589
                                });
                            });
                        }
                    }
                );
            };

            $scope.publish = function () {
                var mes = {};
                mes.projectName = $scope.currProjcet.projectName;
                mes.packageName = $scope.currPackage.name;
                mes.packageId = $scope.currPackage.packageId;

                mes.groupId = $scope.currPackage.groupId;
                mes.artifactId = $scope.currPackage.artifactId;
                mes.version = $scope.currPackage.version;
                mes.packageStatus=$scope.currPackage.packageStatus;
                GillionMsg.showUrl({
                    title: '版本发布',
                    url: '/html2/execute/publish',
                    height: 480,
                    width:650,
                    data: mes,
                    onClose: function (data) {
                        if (angular.isArray(data) && data.length > 0) {
                            Resource("/grule-manager/rulePublish/publish/:id", {
                                id: "@id"
                            }, {
                                "get": {
                                    "failHandler": false
                                }
                            }).get({
                                id: $scope.currPackage.id,
                                unitCaseIds: data,
                                version: $scope.currPackage.version
                            }, function (response) {
                                GillionMsg.showUrl({
                                    title: '发布结果',
                                    url: '/html2/execute/showPublishResult',
                                    data: {result: response},
                                    height: 500,
                                    width: 589,
                                    onClose: function (data) {
                                        $http({
                                            url:"/grule-manager/updatePermission",
                                            method:"GET"
                                        }).success(function(resp){
                                            $rootScope.$sessionAttrs.projectPermission=resp;
                                        });
                                        var href= "/projects/"+$rootScope.currProjcet.id+"/packages/"+data;
                                        $location.url(href);
                                    }
                                });

                            });
                        }
                    }
                });
            };

            $scope.test = function () {
                var mes = {};
                mes.projectName = $scope.currProjcet.projectName;
                mes.packageName = $scope.currPackage.name;
                mes.groupId = $scope.currPackage.groupId;
                mes.artifactId = $scope.currPackage.artifactId;
                GillionMsg.showUrl({
                    title: '用例选择',
                    url: '/html2/execute/test',
                    height: 500,
                    width:500,
                    data: mes,
                    onClose: function (data) {
                        if (angular.isArray(data) && data.length > 0) {
                            Resource("/grule-manager/rulePublish/test/:id", {
                                id: "@id"
                            }, {
                                "get": {
                                    "failHandler": false
                                }
                            }).get({
                                id: $scope.currPackage.id,
                                unitCaseIds: data
                            }, function (response) {
                                $scope.dlg = GillionMsg.showUrl({
                                    title: '编译结果',
                                    url: '/html2/execute/showTestResult',
                                    data: {result: response},
                                    height: 400,
                                    width: 589,
                                    onClose:function(data){
                                        var url =window.location.href.substr(0,window.location.href.indexOf("?")==-1?window.location.href.length:window.location.href.indexOf("?"));
                                        console.log(url);
                                        window.location.href =url+"?testId="+response.testId;
                                    }
                                });
                            });
                        }
                    }
                });
            };

            $scope.log = function () {
                var url = window.location.href;
                var arr = new Array();
                var params;
                arr = url.split("/");
                if (6 < arr.length && arr.length < 8) {
                    params = "?" + arr[5] + "=" + arr[6];
                    window.location.href = "/html2/system#/logManager" + params;
                }
                else if (arr.length > 8) {
                    params = "?" + arr[5] + "=" + arr[6] + "&" + arr[7] + "=" + arr[8];
                    window.location.href = "/html2/system#/logManager" + params;
                }
                else {
                    window.location.href = "/html2/system#/logManager";
                }
            };

            $scope.monitor = function () {
                var url = window.location.href;
                var arr = new Array();
                var params;
                arr = url.split("/");
                if (6 < arr.length && arr.length < 8) {
                    params = "?" + arr[5] + "=" + arr[6];
                    window.location.href = "/html2/system#/monitor" + params;
                }
                else if (arr.length > 8) {
                    params = "?" + arr[5] + "=" + arr[6] + "&" + arr[7] + "=" + arr[8];
                    window.location.href = "/html2/system#/monitor" + params;
                }
                else {
                    window.location.href = "/html2/system#/monitor";
                }
            };

            /**
             * 注销当前用户,跳转回登录页面
             */
            $scope.logout = function(){
                $http.get("/grule-manager/user/logout").success(function(result){
                    if (result.success){
                        window.location.href = "/html2/login/login"
                    }
                });
            };

        }]);

        app.filter('statusFilter', function () {
            return function (input) {
                var valueTypeDict = ['编辑中', '已发布', '已封版'];
                return valueTypeDict[input] || '';
            };
        });

        app.controller('WelcomeController', ['$scope', '$http', '$routeParams', 'RuleSerivce', 'GillionMsg','Resource', function ($scope, $http, $routeParams, RuleSerivce, GillionMsg,Resource) {
            $scope.toggleSearch = function(){
                $scope.showSearchProject = !$scope.showSearchProject;
                if ($scope.showSearchProject) {
                    angular.element('.project-list').css('top', '140px');
                } else {
                    angular.element('.project-list').css('top', '100px');
                }
            };
            var permission=Resource("/grule-manager/permissions/permissionsJudgment");
            $(document).on("click","#permissionsJudgment",function(){
                var packageId=this.getAttribute('data-packageId');
                var url=this.getAttribute('data-href')
                permission.get({packageId:packageId},function(response){
                    if(response.data.success==true){
                        window.location.href=url;
                    }
                });
            });


            $http.get('/grule-manager/projects/allParentList').success(function (data) {
                if(data.reload==true){
                    location.reload();
                }else {
                    $scope.projects = data.projects;
                }
            });
            $scope.selectProject = function (project) {
                RuleSerivce.setCurrentProject(project);
            };
            $http.get('/grule-manager/monitor').success(function (data) {
                $scope.reports = data;
            });
            $scope.createProject = function () {
                GillionMsg.showUrl({
                    title: '新建项目',
                    url: '/html2/rule/create/createProject',
                    width: 400,
                    height: 350,
                    onClose: function (data) {
                        if (data.success) {
                            GillionMsg.alert("提示", "项目新建成功");
                            $http.get('/grule-manager/projects/allList').success(function (data) {
                                if(data.reload==true){
                                    location.reload();
                                }else {
                                    $scope.projects = data.projects;
                                }
                            });
                        }
                    }
                });
            }
            var recentlyPackageClassArr = ["package package-a","package package-b","package package-c","package package-d","package package-e","package package-f"];
            /**
             * 获取最近使用规则包的颜色
             * @param packageId
             * @returns {string}
             */
            $scope.getRecentlyPackageClass = function(packageId){
                var index = parseInt(Hash(packageId) % 6);
                return recentlyPackageClassArr[index];
            }
        }]);

        app.controller('ProjectController', ProjectController);
        app.controller('PackageController', PackageController);
        app.controller('AssemblyController', AssemblyController);
        app.controller('DecisionTableController', DecisionTableController);
        app.controller('DecisionTreeController', DecisionTreeController);
        app.controller('DecisionEditController', DecisionEditController);
        app.controller('DecisionTreeEditController', DecisionTreeEditController);
        app.controller('RuleController', RuleController);
        app.controller('RulePackageInstallController', RulePackageInstallController);
        app.controller('RuleInstallController', RuleInstallController);
        app.controller('RuleAssemblyInstallController', RuleAssemblyInstallController);
        app.controller('DecisionTableInstallController', DecisionTableInstallController);
        app.controller('DecisionTreeInstallController', DecisionTreeInstallController);
        app.controller('VariableController', VariableController);
        app.controller('VersionController', VersionController);
        app.controller('TestController', TestController);
        app.controller('AttributeController', AttributeController);
        app.controller('JdbcController', JdbcController);
        app.controller('RemoteController', RemoteController);
        app.controller('DubboController', DubboController);
        app.controller('SpringCloudController', SpringCloudController);
        app.controller('GroovyShellController', GroovyShellController );
        app.controller('ValidatorController', ValidatorController);

        
        app.config(['$locationProvider', '$routeProvider', 'RuleSerivceProvider', function ($locationProvider, $routeProvider) {
            $routeProvider
                //欢迎页面
                .when('/welcome', {
                    controller: 'WelcomeController',
                    templateUrl: '/html2/rule/welcome'
                })
                //项目编辑页面
                .when('/projects/:projectId', {
                    controller: 'ProjectController',
                    templateUrl: '/html2/rule/project'
                })
                //规则包页面
                .when('/projects/:projectId/packages/:packageId', {
                    controller: 'PackageController',
                    templateUrl: '/html2/rule/package'
                })
                //规则集管理生成
                .when('/projects/:projectId/packages/:packageId/assemblys/:assemblyId', {
                    controller: 'AssemblyController',
                    templateUrl: '/html2/rule/assembly'
                })
                //规则编辑页面
                .when('/projects/:projectId/packages/:packageId/assemblys/:assemblyId/rules/:ruleId', {
                    controller: 'RuleController',
                    templateUrl: '/html2/rule/rule'
                })
                //决策表页面
                .when('/projects/:projectId/packages/:packageId/decisionTables/:tableId', {
                    controller: 'DecisionTableController',
                    templateUrl: '/html2/rule/decisionTable'
                })
                //决策树页面
                .when('/projects/:projectId/packages/:packageId/decisionTrees/:treeId', {
                    controller: 'DecisionTreeController',
                    templateUrl: '/html2/rule/decisionTree'
                })
                //默认
                .otherwise({
                    redirectTo: '/welcome'
                });
        }]);


        app.filter('dataTypeFilter', function() {
            return function(input) {
                var dataTypeDict = {
                    'Integer' : '整型',
                    'Double' : '浮点型',
                    'String' : '字符串',
                    'Boolean' : '布尔',
                    'Date' : '时间',
                    'Object' : '对象类型'
                };
                return dataTypeDict[input] || '';
            };
        });
        app.filter('varExprFilter', function() {
            return function(input) {
                if(input.indexOf("'")==0) {
                    return input.substr(1, input.length-2);
                }else{
                    return input;
                }
            };
        });




        app.filter('valueTypeFilter', function() {
            return function(input) {
                var valueTypeDict = {
                    'Constant' : '常量',
                    'JDBCComponent' : 'JDBC',
                    'Service' : 'java接口',
                    'Rule' :  'Rule',
                    'InParameter' : '传参',
                    'Variable' : '变量',
                    'RemoteService' : 'esb'
                };
                return valueTypeDict[input] || '';
            };
        });

        app.filter('maxLength', function() {
            return function(input, maxLength) {
                if (!input) return '';
                var newLen = 0,
                    newStr = "",
                    chineseRegex = /[^\x00-\xff]/g,
                    singleChar = "",
                    len = input.replace(chineseRegex,"**").length;
                for(var i = 0;i < len;i++) {
                    singleChar = input.charAt(i).toString();
                    if(singleChar.match(chineseRegex) != null) {
                        newLen += 2;
                    } else {
                        newLen++;
                    }
                    if(newLen > maxLength) break;
                    newStr += singleChar;
                }

                if(len > maxLength) {
                    newStr += "...";
                }
                return newStr;
            };
        });

        return app;
    }
);